//
//  PlayMusic.m
//  MarianasTrench
//
//  Created by 王晓晨 on 16/3/22.
//  Copyright © 2016年 王爵. All rights reserved.
//

#import "PlayMusic.h"
#import <AVFoundation/AVFoundation.h>

@interface PlayMusic ()

@end

@implementation PlayMusic

/** 音乐播放器单例 */
+ (PlayMusic *)sharePlayMusic {
    
    static PlayMusic *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        /** 创建播放器 */
        player = [[PlayMusic alloc] init];
        player.avPlayer = [[AVPlayer alloc] init];
    });
    
    return player;
}

/** 添加播放地址 */
- (void)playMusicWithUrlStr:(NSString *)urlStr{
    
    if (_urlStr != urlStr) {
        _urlStr = urlStr;
    }
    _urlStr = [_urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:_urlStr];
    
    self.avPlayItem = [AVPlayerItem playerItemWithURL:url];
    [self.avPlayer replaceCurrentItemWithPlayerItem:_avPlayItem];
    
    [self.avPlayer play];
    _isPlayState = YES;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playToEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }return self;
}

- (void)playToEnd {
    if (self.playToEndBlock) {
        self.playToEndBlock();/**< 回调block >*/
    }
}




- (void)play {
    self.isPlayState = YES;
    [_avPlayer play];
}

- (void)pause {
    self.isPlayState = NO;
    [_avPlayer pause];
}

@end
